﻿using LanguagePolish.EntityModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace LanguagePolish.Models
{
    public class TeachersModel
    {
        public bool CanUserAddTeachers 
        { 
            get 
            { 
                return LinksProvider.Model.CurrentUser.AccountType.AddPermission == true;    
            } 
        }

        public bool CanUserRemoveTeachers
        {
            get 
            {
                return LinksProvider.Model.CurrentUser.AccountType.DeletePermission == true; 
            }
        }

        public bool CanUserEditTeacher
        {
            get { return LinksProvider.Model.CurrentUser.AccountType.EditTeachersPermission == true; }
        }

        public IEnumerable<Teacher> GetTeachersWithFilter(string filter = null)
        {            
            var teacher = LinksProvider.Model.CurrentUser.Teacher;
            if (LinksProvider.Model.IsSeeAll || teacher == null)
            {
                var context = LinksProvider.Model.EntityContext;
                if (string.IsNullOrWhiteSpace(filter))
                    return context.Teachers;
                var res =
                    context.Teachers.ToList()
                        .Where(t => t.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1);
                // TODO: по идее так оптимальнее, но почему-то не работает
                //var res = context.Teachers.Where(s => SqlFunctions.CharIndex(s.Name, filter) != 0);
                return res;
            }
            else
            {
                return new List<Teacher> {teacher};
            }
        }

        public void AddTeacher(Teacher teacher)
        {
            var context = LinksProvider.Model.EntityContext;
            context.Teachers.Add(teacher);
            context.SaveChanges();
        }

        public void RollbackTeacher(Teacher teacher)
        {
            var context = LinksProvider.Model.EntityContext;
            context.Rollback(teacher);
        }

        public void SaveChanges()
        {
            LinksProvider.Model.EntityContext.SaveChanges();
        }

        public void DeleteTeacher(Teacher teacher)
        {
            var context = LinksProvider.Model.EntityContext;
            context.Teachers.Remove(teacher);
            context.SaveChanges();
        }
    }
}
